import os

path = os.path
from importlib import import_module, util
from datetime import datetime
from playwright.sync_api import sync_playwright
import zipfile
import requests
import time

sso = import_module("sso_auth")
sn = import_module("switch_network")
printer = import_module("printer").IndentPrinter(indent=1)
auth_info = None
data_path = os.environ["DATA_PATH"]

base_headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
}
session = requests.Session()


def main():
    global auth_info

    # sn.connect_to_internal()
    if sn.wait_for_system("10.243.24.152", "8080"):
        print("家集客系统已可用")
        printer("[下载数据] 开始")
        printer.add(1)
        with sync_playwright() as p:
            browser = p.chromium.launch(headless=False)
            page = browser.new_page()
            auth_url = sso.login(
                browser=page,
                client_id="18802010086_gmcc_net",
                return_url="http://10.243.24.152:8080/fgios-ui/",
                usr="dwwuyushi",
                pwd="Gmcc2025**##",
                playwright=True,
            )

            page.goto(auth_url)
            page.wait_for_selector("#jk-header-horizontal-menu")
            page.on(
                "response", lambda response: print("<<", response.status, response.url)
            )
            # page.wait_for_selector("#micro-container")

            def handle_download(download):
                print(f"Download started: {download.path()}")
                download.save_as(path.join(data_path,"测试.xlsx"))

            page.on("download", lambda download: handle_download(download))

            def on_web_socket(ws):
                print(f"WebSocket opened: {ws.url}")
                ws.on("framesent", lambda payload: print(payload))
                ws.on("framereceived", lambda payload: print(payload))
                ws.on("close", lambda payload: print("WebSocket closed"))

            page.on("websocket", on_web_socket)

            page.goto("http://10.243.24.152:8080/fgios-ui/report-management/bi/list")
            time.sleep(1500)
        
        # # browser.go_to(iframe_src)
        # browser.wait_for_elements_state(".page-main>div>form")
        # browser.type_text(
        #     selector="#app > section > section > main > div.page-main > div:nth-child(1) > form > div > div:nth-child(3) > div > div > div > input",
        #     txt="放装终端未纳管",
        # )

        # printer("[下载数据] 👏 完成，总耗时<run_time>。", run_time="hh:mm:ss")

        # sn.connect_to_internet()


if __name__ == "__main__":
    main()
